class: center, middle, inverse, title-slide # Introducción a R - Sesión 2 ## Un curso (bastante) rápido ### Octavio Medina ### 2021-11-25 --- class: inverse middle center # Visualización con ggplot2 --- class: inverse middle center Antes de empezar: ```r install.packages("tidyverse") install.packages("hrbrthemes") install.packages("viridis") ``` Y luego: ```r library("tidyverse") library("hrbrthemes") library("viridis") ``` --- # Por qué visualizar? Por qué molestarse? **Dadme razones.** -- - Procesamiento cognitivo - Reconocimiento de patrones - Detección de problemas - Comunicación de conclusiones --- # Por qué visualizar? .pull-left[ .panelset[ .panel[.panel-name[Ejemplo 1] ] .panel[.panel-name[Gorila Real] <img src="data:image/png;base64,#sesion-2/gorila.png" width="100%" /> ] .panel[.panel-name[Gorila Virtual] <img src="data:image/png;base64,#sesion-2/gorila-virtual.png" width="80%" /> ] ] ] .pull-right[ .panelset[ .panel[.panel-name[Ejemplo 2] ] .panel[.panel-name[Tabla]
estado
esperanza_vida
anyo
Louisiana
71.6
1980
Massachusetts
74.8
1980
DC
68.9
1980
Louisiana
74.1
2000
Massachusetts
78.2
2000
DC
72.1
2000
Louisiana
76.1
2018
Massachusetts
80.5
2018
DC
78.6
2018
] .panel[.panel-name[Gráfica] <img src="data:image/png;base64,#sesion-2_files/figure-html/unnamed-chunk-6-1.png" width="90%" /> ] ] ] --- ## La gramática de los gráficos .pull-left[ - La librerÃa de gráficos más popular (y más mejor!) de R es `ggplot2`. Sigue principios basados en la **gramática de los gráficos**. - La gramática de los gráficos es un principio que nos permite definir y organizar un plot según sus diferentes capas. - Esto permite **combinar piezas** para crear prácticamente todo tipo de gráficas. ] .pull-right[ <div class="figure"> <img src="data:image/png;base64,#gog.png" alt="Una gráfica es como una cebolla." width="100%" /> <p class="caption">Una gráfica es como una cebolla.</p> </div> ] --- class: center middle ## Las capas de una gráfica: lo imprescindible <img src="data:image/png;base64,#sesion-2/gog-first.png" width="100%" /> --- ## Las capas de una gráfica: lo imprescindible - **Data**: vuestra base de datos o dataframe, siempre que sea posible en formato `tidy`. - **Aesthetic mapping**: Los `aesthetic mappings` describen cómo las variables de los datos se asignan (mapean) a distintas propiedades visuales (la estética). - **Geometries**: la geometrÃa que queremos usar para mostrar nuestros datos. --- ## Ejemplo - **Data:** `gapminder` - **Aesthetic mapping:** `mean_life_exp` al eje x, `continent` al eje y - **Geometries:** columna, o `geom_col()` <img src="data:image/png;base64,#sesion-2_files/figure-html/unnamed-chunk-9-1.png" width="100%" /> --- ## Ejemplo - **Data:** ? - **Aesthetic mapping:** ? - **Geometries:** ? <img src="data:image/png;base64,#sesion-2_files/figure-html/unnamed-chunk-10-1.png" width="100%" /> --- ## Ejemplo - **Data:** ? - **Aesthetic mapping:** ? - **Geometries:** ? <img src="data:image/png;base64,#sesion-2_files/figure-html/unnamed-chunk-11-1.png" width="100%" /> --- .pull-left[ ## Los mappings - `x` - `y` - `color` - `fill` - `alpha` - `size` ] .pull-left[ ## Los geoms - `geom_point()` - `geom_histogram()` - `geom_line()` - `geom_bar()` - `geom_smooth()` ] --- ## Scatterplot con `geom_point()` .pull-left[ - Un gráfico humilde pero resultón ```r gap_82 <- gapminder %>% filter(year == 1982) ggplot(data = gap_82, * mapping = aes(x = gdpPercap, * y = lifeExp)) + * geom_point() ``` ] .pull-right[ <img src="data:image/png;base64,#sesion-2_files/figure-html/unnamed-chunk-13-1.png" width="100%" /> ] --- ## Scatterplot con `geom_point()` .pull-left[ - Se pueden acumular geoms! Recordad, todo es una cebolla. ```r gap_82 <- gapminder %>% filter(year == 1982) ggplot(data = gap_82, mapping = aes(x = gdpPercap, y = lifeExp)) + * geom_point() + * geom_smooth() ``` ] .pull-right[ <img src="data:image/png;base64,#sesion-2_files/figure-html/unnamed-chunk-15-1.png" width="100%" /> ] --- ## Barras con `geom_bar()` y `geom_col()` .pull-left[ - Las barras son un poco especiales, porque se pueden usar para **contar observaciones** o para **mostrar otras variables.** - Para lo primero, usaremos `geom_bar()` (ojo con los mappings!), para lo demás `geom_col()` suele ser más cómodo. ```r ggplot(data = gap_82, mapping = aes(x = gdpPercap, y = lifeExp)) + * geom_bar() ``` ] .pull-right[ <img src="data:image/png;base64,#sesion-2_files/figure-html/unnamed-chunk-17-1.png" width="100%" /> ] --- ## Histograma con `geom_histogram()` .pull-left[ - Notáis algo similar? ```r ggplot(data = gap_82, * mapping = aes(x = gdpPercap)) + * geom_histogram() ``` ] .pull-right[ <img src="data:image/png;base64,#sesion-2_files/figure-html/unnamed-chunk-19-1.png" width="100%" /> ] --- class: center middle # Probando los mappings: breve demostración --- class: inverse center middle # themes y facets: dos elementos más --- # `themes` and co. .pull-left[ - Los `themes` se pueden usar para cambiar la apariencia o estilo del gráfico. ```r install.packages("hrbrthemes") library(hrbrthemes) ggplot(data = gap_82, mapping = aes(x = gdpPercap)) + geom_histogram() + * theme_ipsum() ``` ] .pull-right[ <img src="data:image/png;base64,#sesion-2_files/figure-html/unnamed-chunk-21-1.png" width="100%" /> ] --- # `themes` and co. .pull-left[ - Los `facets` nos simplifican el proceso de visualizar diferencias entre categorÃas. ```r ggplot(data = gap_82, mapping = aes(x = gdpPercap)) + geom_histogram() + * theme_minimal() + * facet_wrap(~continent) ``` ] .pull-right[ <img src="data:image/png;base64,#sesion-2_files/figure-html/unnamed-chunk-23-1.png" width="100%" /> ] --- # Escalas de colores .pull-left[ - Las escalas de colores siguen la lógica de los mappinngs. - Para añadir una escala discreta para `color`, podemos añadir `scale_color_*`. Si es para fill, entonces `scale_fill_*`. - Las escalas `viridis`, del paquete del mismo nombre, suelen ser una buena opción. Pero hay muchas! ```r ggplot(data = gap_82, mapping = aes(x = gdpPercap, y = lifeExp, color = continent)) + geom_point() + theme_ipsum() + * facet_wrap(~continent) + * scale_color_viridis_d() ``` ] .pull-right[ <img src="data:image/png;base64,#sesion-2_files/figure-html/unnamed-chunk-25-1.png" width="80%" /> ] --- class: inverse center middle ## AnatomÃa de un ggplot --- count: false .panel1-my_gap-auto[ ```r *gapminder ``` ] .panel2-my_gap-auto[ ``` # A tibble: 1,704 × 6 country continent year lifeExp pop gdpPercap <fct> <fct> <int> <dbl> <int> <dbl> 1 Afghanistan Asia 1952 28.8 8425333 779. 2 Afghanistan Asia 1957 30.3 9240934 821. 3 Afghanistan Asia 1962 32.0 10267083 853. 4 Afghanistan Asia 1967 34.0 11537966 836. 5 Afghanistan Asia 1972 36.1 13079460 740. 6 Afghanistan Asia 1977 38.4 14880372 786. 7 Afghanistan Asia 1982 39.9 12881816 978. 8 Afghanistan Asia 1987 40.8 13867957 852. 9 Afghanistan Asia 1992 41.7 16317921 649. 10 Afghanistan Asia 1997 41.8 22227415 635. # … with 1,694 more rows ``` ] --- count: false .panel1-my_gap-auto[ ```r gapminder %>% * filter(year == 1982) ``` ] .panel2-my_gap-auto[ ``` # A tibble: 142 × 6 country continent year lifeExp pop gdpPercap <fct> <fct> <int> <dbl> <int> <dbl> 1 Afghanistan Asia 1982 39.9 12881816 978. 2 Albania Europe 1982 70.4 2780097 3631. 3 Algeria Africa 1982 61.4 20033753 5745. 4 Angola Africa 1982 39.9 7016384 2757. 5 Argentina Americas 1982 69.9 29341374 8998. 6 Australia Oceania 1982 74.7 15184200 19477. 7 Austria Europe 1982 73.2 7574613 21597. 8 Bahrain Asia 1982 69.1 377967 19211. 9 Bangladesh Asia 1982 50.0 93074406 677. 10 Belgium Europe 1982 73.9 9856303 20980. # … with 132 more rows ``` ] --- count: false .panel1-my_gap-auto[ ```r gapminder %>% filter(year == 1982) %>% * ggplot() ``` ] .panel2-my_gap-auto[ <img src="data:image/png;base64,#sesion-2_files/figure-html/my_gap_auto_03_output-1.png" width="100%" /> ] --- count: false .panel1-my_gap-auto[ ```r gapminder %>% filter(year == 1982) %>% ggplot() + * aes(x = gdpPercap) ``` ] .panel2-my_gap-auto[ <img src="data:image/png;base64,#sesion-2_files/figure-html/my_gap_auto_04_output-1.png" width="100%" /> ] --- count: false .panel1-my_gap-auto[ ```r gapminder %>% filter(year == 1982) %>% ggplot() + aes(x = gdpPercap) + * aes(y = lifeExp) ``` ] .panel2-my_gap-auto[ <img src="data:image/png;base64,#sesion-2_files/figure-html/my_gap_auto_05_output-1.png" width="100%" /> ] --- count: false .panel1-my_gap-auto[ ```r gapminder %>% filter(year == 1982) %>% ggplot() + aes(x = gdpPercap) + aes(y = lifeExp) + * geom_point() ``` ] .panel2-my_gap-auto[ <img src="data:image/png;base64,#sesion-2_files/figure-html/my_gap_auto_06_output-1.png" width="100%" /> ] --- count: false .panel1-my_gap-auto[ ```r gapminder %>% filter(year == 1982) %>% ggplot() + aes(x = gdpPercap) + aes(y = lifeExp) + geom_point() + * aes(color = continent) ``` ] .panel2-my_gap-auto[ <img src="data:image/png;base64,#sesion-2_files/figure-html/my_gap_auto_07_output-1.png" width="100%" /> ] --- count: false .panel1-my_gap-auto[ ```r gapminder %>% filter(year == 1982) %>% ggplot() + aes(x = gdpPercap) + aes(y = lifeExp) + geom_point() + aes(color = continent) + * aes(size = pop) ``` ] .panel2-my_gap-auto[ <img src="data:image/png;base64,#sesion-2_files/figure-html/my_gap_auto_08_output-1.png" width="100%" /> ] --- count: false .panel1-my_gap-auto[ ```r gapminder %>% filter(year == 1982) %>% ggplot() + aes(x = gdpPercap) + aes(y = lifeExp) + geom_point() + aes(color = continent) + aes(size = pop) + * theme_ipsum() ``` ] .panel2-my_gap-auto[ <img src="data:image/png;base64,#sesion-2_files/figure-html/my_gap_auto_09_output-1.png" width="100%" /> ] --- count: false .panel1-my_gap-auto[ ```r gapminder %>% filter(year == 1982) %>% ggplot() + aes(x = gdpPercap) + aes(y = lifeExp) + geom_point() + aes(color = continent) + aes(size = pop) + theme_ipsum() + * labs(title = "PIB y esperanza de vida en 1982", * subtitle = "Datos del proyecto Gapminder, creado por Hans Rosling", * x = "PIB per cápita", * y = "Esperanza de vida", * color = "Continente", * size = "Población") ``` ] .panel2-my_gap-auto[ <img src="data:image/png;base64,#sesion-2_files/figure-html/my_gap_auto_10_output-1.png" width="100%" /> ] --- count: false .panel1-my_gap-auto[ ```r gapminder %>% filter(year == 1982) %>% ggplot() + aes(x = gdpPercap) + aes(y = lifeExp) + geom_point() + aes(color = continent) + aes(size = pop) + theme_ipsum() + labs(title = "PIB y esperanza de vida en 1982", subtitle = "Datos del proyecto Gapminder, creado por Hans Rosling", x = "PIB per cápita", y = "Esperanza de vida", color = "Continente", size = "Población") + * scale_color_viridis_d() ``` ] .panel2-my_gap-auto[ <img src="data:image/png;base64,#sesion-2_files/figure-html/my_gap_auto_11_output-1.png" width="100%" /> ] --- count: false .panel1-my_gap-auto[ ```r gapminder %>% filter(year == 1982) %>% ggplot() + aes(x = gdpPercap) + aes(y = lifeExp) + geom_point() + aes(color = continent) + aes(size = pop) + theme_ipsum() + labs(title = "PIB y esperanza de vida en 1982", subtitle = "Datos del proyecto Gapminder, creado por Hans Rosling", x = "PIB per cápita", y = "Esperanza de vida", color = "Continente", size = "Población") + scale_color_viridis_d() ``` ] .panel2-my_gap-auto[ <img src="data:image/png;base64,#sesion-2_files/figure-html/my_gap_auto_12_output-1.png" width="100%" /> ] <style> .panel1-my_gap-auto { color: black; width: 38.6060606060606%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel2-my_gap-auto { color: black; width: 59.3939393939394%; hight: 32%; float: left; padding-left: 1%; font-size: 80% } .panel3-my_gap-auto { color: black; width: NA%; hight: 33%; float: left; padding-left: 1%; font-size: 80% } </style> --- class: inverse center middle # Preguntas?